package com.thlws.rocketmq;

import java.util.List;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;

public class ConsumerDemo {

	
	public static void main(String[] args) throws InterruptedException, MQClientException {
	    
        //声明并初始化一个consumer
        //需要一个consumer group名字作为构造方法的参数，这里为consumer1
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consumer_orders_group");

//        consumer.setVipChannelEnabled(false);
        //同样也要设置NameServer地址
        consumer.setNamesrvAddr("47.100.122.135:9876");
        
        //并发时设置
        consumer.setConsumeThreadMin(10);
        consumer.setConsumeThreadMax(20);
        
        //表示消费端最大消费消息数量是10条，需要注意的是：
        //若comsumer是运行状态，接收的消息仍旧是1条1条消费的
        //若consumer发送消息前是停止状态，发送完毕后，再启动comsumer，此时会按照设置的消息大小消费
        consumer.setConsumeMessageBatchMaxSize(1);

        //这里设置的是一个consumer的消费策略
        //CONSUME_FROM_LAST_OFFSET 默认策略，从该队列最尾开始消费，即跳过历史消息
        //CONSUME_FROM_FIRST_OFFSET 从队列最开始开始消费，即历史消息（还储存在broker的）全部消费一遍
        //CONSUME_FROM_TIMESTAMP 从某个时间点开始消费，和setConsumeTimestamp()配合使用，默认是半个小时以前
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);

        //设置consumer所订阅的Topic和Tag，*代表全部的Tag
        consumer.subscribe("orders", "tag1");

        //设置一个Listener，主要进行消息的逻辑处理
        consumer.registerMessageListener(new MessageListenerConcurrently() {

            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {

            	MessageExt msg = msgs.get(0);
            	
            	try {
//					for (MessageExt msg : msgs) {
//						System.out.println("收到msg: " + new String(msg.getBody()));
//					}
            		
            		System.out.println("Consumer1 收到msg: " + new String(msg.getBody()));
            		
					//System.out.println(Thread.currentThread().getName() + " Receive New Messages: " + msgs);
				} catch (Exception e) {
					e.printStackTrace();
					if(msg.getReconsumeTimes() == 5) {
						System.out.println("消息重试5次仍旧失败，记录日志，返回成功，不再进入重试流程");
						  return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
					}
				}
				
                
                //返回消费状态
                //CONSUME_SUCCESS 消费成功
                //RECONSUME_LATER 消费失败，需要稍后重新消费,内置重试策略 1s 5s 10s ... 2h 等
            	
            	
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        

        //调用start()方法启动consumer
        consumer.start();
        System.out.println("Consumer Started.");
        
        
    }
	
	
}
